package cn.faifai.desktop.view.components.treeDirectory;

import cn.faifai.common.constant.Constants;
import cn.faifai.desktop.api.FileUrlController;
import cn.faifai.desktop.events.FileSecondaryClickEvent;
import cn.faifai.desktop.events.TreeNodeIsSelectedEvent;
import cn.faifai.framework.utils.SingleEvenBus;
import cn.faifai.common.utils.SpringContextUtil;
import cn.faifai.desktop.utils.VirtualThreadPoolManager;
import cn.faifai.desktop.view.components.menus.FileTreeItemMenu;
import com.google.common.eventbus.EventBus;
import javafx.concurrent.Task;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class FileBrowser extends VBox {
    private TreeView<DirectoryItem> treeView; // 树组件
    @Autowired
    private FileUrlController fileUrlController;

    private  EventBus eventBus;

    // 初始化界面
    public FileBrowser initUI() {
        eventBus = SingleEvenBus.getInstance();
        log.info("初始化树目录");
        // 创建树形结构
        TreeItem<DirectoryItem> root = new TreeItem<>(new DirectoryItem("我的电脑", Constants.MY_COMPUTER));
        // 创建TreeView并设置模型
        treeView = new TreeView<>(root);
        treeView.setShowRoot(true);

        // 设置双击监听器
        treeView.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) { // 检查是否是双击
                log.info("双击事件");
                TreeItem<DirectoryItem> selectedItem = treeView.getSelectionModel().getSelectedItem();
                loadChildren(selectedItem);
            }
            if (event.getClickCount() == 1){
                log.info("单击事件");
                if (event.getButton() == MouseButton.PRIMARY){
                    log.info("开始添加选中事件");
                    TreeItem<DirectoryItem> selectedItem = treeView.getSelectionModel().getSelectedItem();
                    eventBus.post(new TreeNodeIsSelectedEvent(selectedItem.getValue().path));
                    FileTreeItemMenu.getMenu().hide();
                }
                if(event.getButton() == MouseButton.SECONDARY){
                    TreeItem<FileBrowser.DirectoryItem> selectedItem = treeView.getSelectionModel().getSelectedItem();
                    if (selectedItem != null){
                        System.out.println("选中了：" + selectedItem.getValue().getName());
                        FileTreeItemMenu.getMenu().hide();
                        FileTreeItemMenu.getMenu().show(treeView, event.getScreenX(), event.getScreenY());
                        SingleEvenBus.getInstance().post(new FileSecondaryClickEvent(0l,selectedItem.getValue().getPath()));
                    }
                    log.info("右键事件");
                }
            }
        });

        treeView.setMaxWidth(Double.MAX_VALUE);  // 允许横向无限扩展
        treeView.setMaxHeight(Double.MAX_VALUE); // 允许纵向无限扩展

        VBox.setVgrow(treeView, Priority.ALWAYS); // 给树组件分配扩展优先权

        // 添加到布局
        this.getChildren().add(treeView);
        return this;
    }

    // 异步加载子节点
    private void loadChildren(TreeItem<DirectoryItem> parentItem) {
        log.info("加载子节点");

        String parentPath = parentItem.getValue().getPath();

        Task<List<DirectoryItem>> loadTask = new Task<>() {
            @Override
            protected List<DirectoryItem> call() throws Exception {
                List<String> subPath = fileUrlController.getSubPath2(parentPath).getDirectories();
                List<DirectoryItem> directoryItems =
                        subPath.stream()
                                .map(item -> new DirectoryItem(
                                        // 判断返回的是否是根目录，根目录无法获取文件名，用根目录显示
                                        Paths.get(item).getNameCount() == 0 || Paths.get(item).equals(Paths.get(item).getRoot()) ?
                                        Paths.get(item).getRoot().toString() : Paths.get(item).getFileName().toString(),
                                        item))
                                .collect(Collectors.toList());
                return directoryItems;
            }
        };

        loadTask.setOnSucceeded(e -> {
            List<DirectoryItem> children = loadTask.getValue();
            parentItem.getChildren().clear();
            parentItem.getChildren().addAll(
                    children.stream()
                            .map(item -> new TreeItem<>(item))
                            .toList()
            );
            parentItem.setExpanded(true);

            parentItem.getChildren().stream().forEach(item -> {
                if (SpringContextUtil.getContext().getBean(FileUrlController.class).hasSubPath(item.getValue().path)){
                    item.getChildren().add(new TreeItem<>());
                }
            });
        });

        VirtualThreadPoolManager.getInstance().submit(loadTask::run);
    }

    // 定义数据模型
    @Getter
    public static class DirectoryItem {
        private final String path;
        private final String name;

        public DirectoryItem(String name, String path){
            this.name = name;
            this.path = path;
        }

        @Override
        public String toString() {
            return name;
        }
    }
}
